package com.ruoyi.system.domain;

import com.ruoyi.common.utils.poi.ExcelUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;

public class DynamicOrderExcelUtil {
    private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);

    /**
     * 生成动态订餐模板
     *
     * @param response 响应对象
     * @param trainingName 培训名称
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param sheetName sheet名称
     * @throws IOException IO异常
     */
    public static void generateOrderTemplate(HttpServletResponse response, String trainingName, Date startDate, Date endDate, String sheetName) throws IOException {
        List<String> mealColumns = generateMealColumns(startDate, endDate);
        Workbook workbook = new SXSSFWorkbook();
        Sheet sheet = workbook.createSheet(sheetName);

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.setHeight((short) (20 * 20)); // 设置行高

        // 固定列（包括新增的培训名称和培训时间列）
        String[] fixedColumns = {"序号", "培训名称", "培训时间","姓名","员工编号",  "性别", "部门", "电话", "邮箱", };
        for (int i = 0; i < fixedColumns.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(fixedColumns[i]);
            CellStyle cellStyle = createHeaderCellStyle(workbook);
            cell.setCellStyle(cellStyle);
        }

        // 动态用餐列
        int columnIndex = fixedColumns.length;
        for (String mealColumn : mealColumns) {
            Cell cell = headerRow.createCell(columnIndex++);
            cell.setCellValue(mealColumn);
            CellStyle cellStyle = createHeaderCellStyle(workbook);
            cell.setCellStyle(cellStyle);
        }

        // 创建示例行
        Row sampleRow = sheet.createRow(1);
        // 按照新的顺序创建示例值
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String trainingDateStr = dateFormat.format(startDate) + " 至 " + dateFormat.format(endDate);

        // 创建居中对齐的示例单元格样式
        CellStyle sampleStyle = createSampleCellStyle(workbook);

        // 先设置固定的示例值
        Cell indexCell = sampleRow.createCell(0); // 序号
        indexCell.setCellValue("1");
        indexCell.setCellStyle(sampleStyle);

        Cell trainingNameCell = sampleRow.createCell(1); // 培训名称
        trainingNameCell.setCellValue(trainingName);
        trainingNameCell.setCellStyle(sampleStyle);

        Cell trainingDateCell = sampleRow.createCell(2); // 培训时间
        trainingDateCell.setCellValue(trainingDateStr);
        trainingDateCell.setCellStyle(sampleStyle);

        Cell nameCell = sampleRow.createCell(3); // 姓名
        nameCell.setCellValue("张三");
        nameCell.setCellStyle(sampleStyle);

        Cell empIdCell = sampleRow.createCell(4); // 员工编号
        empIdCell.setCellValue("EMP001");
        empIdCell.setCellStyle(sampleStyle);

        Cell genderCell = sampleRow.createCell(5); // 性别
        genderCell.setCellValue("");
        genderCell.setCellStyle(sampleStyle);

        Cell departmentCell = sampleRow.createCell(6); // 部门
        departmentCell.setCellValue("");
        departmentCell.setCellStyle(sampleStyle);

        Cell phoneCell = sampleRow.createCell(7); // 电话
        phoneCell.setCellValue("");
        phoneCell.setCellStyle(sampleStyle);

        Cell emailCell = sampleRow.createCell(8); // 邮箱
        emailCell.setCellValue("");
        emailCell.setCellStyle(sampleStyle);

        // 用餐列示例值
        for (int i = fixedColumns.length; i < mealColumns.size() + fixedColumns.length; i++) {
            Cell cell = sampleRow.createCell(i);
            cell.setCellValue("是/否");
            cell.setCellStyle(sampleStyle);
        }

        // 设置列宽
        for (int i = 0; i < mealColumns.size() + fixedColumns.length; i++) {
            sheet.setColumnWidth(i, 20 * 256);
        }

        // 输出Excel
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + java.net.URLEncoder.encode("订餐模板-" + trainingName + ".xlsx", "UTF-8") + "\"");
        OutputStream out = response.getOutputStream();
        workbook.write(out);
        out.flush();
        out.close();
        workbook.close();
    }

    /**
     * 生成用餐列名
     */
    private static List<String> generateMealColumns(Date startDate, Date endDate) {
        List<String> columns = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        while (!calendar.getTime().after(endDate)) {
            String dateStr = sdf.format(calendar.getTime());
            columns.add(dateStr + "午餐");
            columns.add(dateStr + "晚餐");
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        return columns;
    }

    /**
     * 创建表头单元格样式
     */
    private static CellStyle createHeaderCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        Font font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }

    /**
     * 创建示例行单元格样式
     */
    private static CellStyle createSampleCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }
}